package com.nervenets.general.filter;

import cn.hutool.core.io.resource.ResourceUtil;
import com.nervenets.general.config.ApplicationProperties;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
public class SecretUrlFilter implements Filter {
    private final ApplicationProperties applicationProperties;

    public SecretUrlFilter(ApplicationProperties applicationProperties) {
        this.applicationProperties = applicationProperties;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("SecretUrlFilter uri: {}", requestURI);
        HttpSession session = request.getSession();
        Object sessionValue = session.getAttribute("SecretUrlFilter");
        log.info("SecretUrlFilter session: {}", sessionValue);
        ApplicationProperties.SecretUrl secretUrl = applicationProperties.getSecretUrl();

        if (secretUrl.isEnable()) {
            if (ApplicationProperties.SecretUrl.LOGIN_ACTION.equals(requestURI)) {
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                if (secretUrl.getUsername().equals(username) && secretUrl.getPassword().equals(password)) {
                    session.setAttribute("SecretUrlFilter", "SecretUrlFilter");
                    response.sendRedirect(request.getHeader("referer"));
                    return;
                } else {
                    servletResponse.setContentType("application/json");
                    servletResponse.setCharacterEncoding("UTF-8");
                    servletResponse.getWriter().write("登录失败");
                    return;
                }
            } else if (null == sessionValue) {
                servletResponse.setContentType("text/html");
                servletResponse.setCharacterEncoding("UTF-8");
                servletResponse.getWriter().write(ResourceUtil.readUtf8Str("template/login.html"));
                return;
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

}
